﻿using QModel;
using Microsoft.Phone.Controls;
using System;
using System.Diagnostics;
using QLibrary.Helper;
using System.Collections.Generic;

namespace QCats
{
    public partial class MainPage : PhoneApplicationPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void LoginBrowser_Navigating(object sender, NavigatingEventArgs e)
        {
            //Debug.WriteLine("url :" + e.Uri.ToString());
            string url = e.Uri.ToString();
            if (url.Contains("access_token"))
            {
                string parseUrl = url.Split('#')[1];
                Dictionary<string,object> dic = ParamHelper.BuildDictionary(parseUrl);
                OauthEntity oauthEntity = new OauthEntity();
                oauthEntity.RRAccessToken = dic["access_token"] as string;
                oauthEntity.ExpiresIn = dic["expires_in"] as string;
                Constants.RROauthEntity = oauthEntity;
                IsolatedStorageHelper.AddToSetting("OauthEntity", oauthEntity);
                NavigateToMainView();
            }
        }

        private void NavigateToMainView()
        {
            this.NavigationService.Navigate(new Uri("/Views/InformationView.xaml", UriKind.Relative));
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            OauthEntity oauthEntity = IsolatedStorageHelper.GetSetting<OauthEntity>("OauthEntity");
            if (string.IsNullOrEmpty(oauthEntity.RRAccessToken))
            {
                string accredit = string.Format("{0}client_id={1}&response_type=token&redirect_uri={2}&display=touch"
                , Constants.RRLoginUrl, Constants.RRkey, Constants.RRRedirectUrl);
                LoginBrowser.Navigate(new Uri(accredit, UriKind.Absolute));
            }
            else
            {
                Constants.RROauthEntity = oauthEntity;
                NavigateToMainView();
            }
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
        }
    }
}
